package com.cloud.sample.support;

import lombok.Data;
import org.jsoup.Jsoup;
import org.jsoup.safety.Safelist;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Set;

@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "xss")
public class XSSCleaner {
    /**
     * 安全标签
     */
    private Set<String> safeTags;

    /**
     * 安全属性
     */
    private Set<String> safeAttrs;

    /**
     * 清理数据
     *
     * @param bodyHtml
     * @return
     */
    public String clean(String bodyHtml) {
        if (CollectionUtils.isEmpty(safeTags) || CollectionUtils.isEmpty(safeAttrs)) {
            return bodyHtml;
        }
        bodyHtml = bodyHtml.replaceAll("(?i)javascript", "");
        Safelist safelist = new Safelist();
        safelist.addTags(safeTags.toArray(new String[safeTags.size()]));
        safelist.addAttributes(":all", safeAttrs.toArray(new String[safeAttrs.size()]));
        return Jsoup.clean(bodyHtml, safelist);
    }
}
